package com.zyasdk;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;

import com.deng.myxutils.XUtil;
import com.google.gson.Gson;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.Tag;
import com.zyasdk.deng.DownLoadService;
import com.zyasdk.deng.SecondActivity;
import com.zyasdk.enums.AdType;
import com.zyasdk.enums.KVType;
import com.zyasdk.model.PackageAds;
import com.zyasdk.pushAction.ActionTypeAdData;
import com.zyasdk.pushAction.ClientId;
import com.zyasdk.service.PidCidService;
import com.zyasdk.util.GoogleUtil;
import com.zyasdk.util.JSONHelper;
import com.zyasdk.util.ZYALogUtils;
import com.zyasdk.util.LanguageUtil;
import com.zyasdk.util.OperatorUtil;
import com.zyasdk.util.SP;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.x;

import java.util.Locale;

public class GetuiReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        String packageName = context.getPackageName();
        String appid = null;
        final Gson gson = new Gson();
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(packageName,

                    PackageManager.GET_META_DATA);
            if (appInfo.metaData != null) {
                appid = appInfo.metaData.getString("PUSH_APPID");
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        if (appid != null && intent.getAction().equals("com.igexin.sdk.action." + appid)) {
            Bundle bundle = intent.getExtras();
            switch (bundle.getInt(PushConsts.CMD_ACTION)) {
                case PushConsts.GET_MSG_DATA:
                    // 获取透传数据
                    //String appid1 = bundle.getString("appid");
                    byte[] payload = bundle.getByteArray("payload");
                    String taskid = bundle.getString("taskid");
                    String messageid = bundle.getString("messageid");

                    // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                    boolean result = PushManager.getInstance().sendFeedbackMessage(context,
                            taskid, messageid, 90001);
                    /*
                    JSONObject json = new JSONObject();
	                try {
		                json.put("ActionType","1");
		                json.put("PacketId","402");
		                json.put("AdType","1");
	                } catch (JSONException e) {
	                    e.printStackTrace();
	                }
	                ZYALogUtils.d("encodeToString: " + Base64.encodeToString(json.toString().getBytes(),
	                Base64.DEFAULT));
	                */
                    if (payload != null) {
                        String data = null;
                        boolean isGoole;
                        boolean isOperator;
                        int ActionType = 0;
                        int packetId = 0;
                        JSONObject json = null;
                        try {
                            data = new String(Base64.decode(new String(payload),
                                    Base64.DEFAULT));
                            Log.e("zlog", "data " + data);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (data != null) {
                            try {
                                json = new JSONObject(data);
                                packetId = json.getInt("PacketId");
//                                ActionType = json.getInt("ActionType");
                                //判断推送的是运营商用户
                                isOperator = OperatorUtil.getOperator(json.getString("mobi"), context);
                                //判断是否推送的是google用户
                                isGoole = GoogleUtil.isGoogleUser(json.getString("google"), context);
                                if (isGoole && isOperator) {
                                    ActionType = json.getInt("ActionType");
                                } else {
                                    ActionType = 6;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        int pId = Integer.parseInt(KVType.PACKID.getValue(context));
                        if (pId != packetId) {
                            ZYALogUtils.d("packetId is error,send id is:" + packetId + "::self id is:"
                                    + pId);
                            return;
                        }


                        String PropackId = null;
                        ActionTypeAdData AdData = null;
                        try {
                            AdData = JSONHelper.parseObject(json, ActionTypeAdData.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        switch (ActionType) {
                            case 1:
                                //	                    		ActionTypeAdData AdData = null;
                                //	                    		try {
                                //	                    			AdData = JSONHelper
                                // .parseObject(json, ActionTypeAdData.class);
                                //	        					} catch (JSONException e) {
                                //	        						e.printStackTrace();
                                //	        					}
                                SP.getInstance().put(context, "actiontype", ActionType + "");
                                if (null != AdData) {
                                    String xx = AdData.getPropackId();
                                    switch (AdData.getAdType()) {
                                        case 1:
                                            if (TextUtils.isEmpty(xx) || xx.equals("-1")) { //随机
                                                SP.getInstance().put(context, "chapingdata",
                                                        xx);
                                                new WU(context).showAds(AdType.AD);
                                            } else {  // 指定插屏
                                                SP.getInstance().put(context, "chapingdata",
                                                        xx);
                                                new WU(context).showAds(AdType.AD);
                                            }
                                            // 弹屏
                                            break;
                                        case 6:
                                            new WU(context).showAds(AdType.NOTIFIS);
                                            break;
                                        case 7:
                                            new WU(context).showAds(AdType.SILENCE);
                                            break;

                                        default:
                                            ZYALogUtils.d("bad adType:" + AdData.getAdType());
                                            break;
                                    }
                                }
                                break;
                            case 2:
                                String packId = KVType.PACKID.getValue(context);
                                String pBindKey = KVType.PBINDKEY.getValue(context);
                                String cid = ClientId.getClientId();
                                new PidCidService(context).AddPidCid(pBindKey, packId, cid);
                                break;
                            case 3:
                                String apkPackage = null;
                                try {
                                    json = new JSONObject(data);
                                    apkPackage = json.getString("packageName");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                if (apkPackage != null) {
                                    intent = context.getPackageManager()
                                            .getLaunchIntentForPackage(apkPackage);
                                    if (intent != null) {
                                        context.startActivity(intent);
                                    } else {
                                        ZYALogUtils.d("intent is null");
                                    }
                                }
                                break;
                            case 4:
                                PropackId = AdData.getPropackId();   // 服务器下发参数
                                String langCode = LanguageUtil.getCountry(context);
                                if (null != AdData) {
                                    switch (AdData.getAdType()) {
                                        case 1:

                                            if (TextUtils.isEmpty(PropackId) || PropackId.equals
                                                    ("-1")) {  // 空,随机

                                                // String url=http://admin.zhuoyian
                                                // .com:9071/Api/GetLink?packid=529&spread=8
                                                // &language=CN
                                                //	String
                                                // url="http://192.168.1.172:8888/project
                                                // -manager
                                                // /Api/GetLink?spread=8&language="+langCode
                                                // +"&packid="+packetId;	 //本地
                                                String url = "http://pm.zhuoyian" +
                                                        ".com/Api/GetLink?spread=8&language=" +
                                                        langCode + "&packid=" + packetId;     //
                                                // 服务器
                                                XUtil.Get(url, null, new CommonCallback
                                                        <String>() {

                                                    @Override
                                                    public void onCancelled(CancelledException
                                                                                    arg0) {
                                                        Log.e("zlog", "XUtil" + "onCancelled");
                                                    }

                                                    @Override
                                                    public void onError(Throwable arg0, boolean
                                                            arg1) {
                                                        Log.e("zlog", "XUtil" + "onError");
                                                    }

                                                    @Override
                                                    public void onFinished() {
                                                        Log.e("zlog", "XUtil" + "onFinished");
                                                    }

                                                    @Override
                                                    public void onSuccess(String result) {
                                                        Log.i("GET_CLIENTID0~", "result:" + result);
                                                        final PackageAds packageAds = gson
                                                                .fromJson(result, PackageAds
                                                                        .class);
                                                        Log.e("zlog", "XUtil" + "packageAds" +
                                                                ".toString" +
                                                                "():" + packageAds.toString());

                                                        View view = View.inflate(context, R
                                                                .layout.dialog_view, null);
                                                        ImageView iv = (ImageView) view
                                                                .findViewById(R.id.imageView1);

                                                        //x.image().bind(iv, "https://ss2.baidu
                                                        // .com/6ONYsjip0QIZ8tyhnq/it/u
                                                        // =2838571217,
                                                        // 3958117776&fm=80&w=179&h=119&img
                                                        // .JPEG");
                                                        x.image().bind(iv, "http://pm.zhuoyian" +
                                                                ".com/" + packageAds
                                                                .getImagefile
                                                                        ());
                                                        //findViewById(id)是在setContentView()
                                                        // 中的View中
                                                        final AlertDialog.Builder builder = new
                                                                AlertDialog.Builder(context);
                                                        builder.setView(view);

                                                        final AlertDialog dialog = builder
                                                                .create();
                                                        dialog.getWindow().setType(WindowManager
                                                                .LayoutParams
                                                                .TYPE_SYSTEM_ALERT);
                                                        dialog.show();
                                                        view.setOnClickListener(new
                                                                                        OnClickListener() {

                                                                                            @Override
                                                                                            public void onClick(View v) {

                                                                                                dialog.dismiss();

                                                                                                // 跳入webview
                                                                                                String goUrl = packageAds
                                                                                                        .getContentUrl();
                                                                                                ZYALogUtils.d("goUrl:" + goUrl);
                                                                                                if (TextUtils.isEmpty(goUrl)) {
                                                                                                    return;
                                                                                                }
                                                                                                if (!goUrl.contains(".apk")) {
                                                                                                    Intent intent1 = new Intent
                                                                                                            (context,
                                                                                                                    SecondActivity
                                                                                                                            .class);
                                                                                                    intent1.setFlags(Intent
                                                                                                            .FLAG_ACTIVITY_NEW_TASK);
                                                                                                    intent1.putExtra("goUrl",
                                                                                                            goUrl);
                                                                                                    context.startActivity(intent1);
                                                                                                } else {
                                                                                                    Intent sIntent = new Intent
                                                                                                            (context,
                                                                                                                    DownLoadService.class);
                                                                                                    //	sIntent.putExtra
                                                                                                    // ("downUrl", "http://pm
                                                                                                    // .zhuoyian
                                                                                                    // .com/upload/propackage/APK/676E7FE5FFFFFFE20E5FC4B46900A100.apk");
                                                                                                    sIntent.putExtra("downUrl",
                                                                                                            goUrl);
                                                                                                    context.startService(sIntent);
                                                                                                }
                                                                                                // apk 下载

		                					
		             					/*   Intent intent= new Intent();
                                           intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		             					    intent.setAction("android.intent.action.VIEW");    
		             					    Uri content_url = Uri.parse(packageAds.getContentUrl()
		             					    );
		             					    intent.setData(content_url);  
		             					     context.startActivity(intent);*/


                                                                                            }
                                                                                        });
                                                    }
                                                });

                                            } else {
                                                //String
                                                // url="http://192.168.1.172:8888/project
                                                // -manager
                                                // /Api/GetLink?PropackId="+PropackId;		// 本地调试
                                                String url = "http://pm.zhuoyian" +
                                                        ".com/Api/GetLink?PropackId=" +
                                                        PropackId;
                                                // 服务器

                                                XUtil.Get(url, null, new
                                                        CommonCallback<String>() {
                                                            @Override
                                                            public void onCancelled
                                                                    (CancelledException
                                                                             arg0) {
                                                            }

                                                            @Override
                                                            public void onError(Throwable arg0,
                                                                                boolean
                                                                                        arg1) {
                                                            }

                                                            @Override
                                                            public void onFinished() {
                                                            }

                                                            @Override
                                                            public void onSuccess(String result) {
                                                                final PackageAds packageAds = gson
                                                                        .fromJson(result, PackageAds
                                                                                .class);

                                                                View view = View.inflate(context, R
                                                                        .layout.dialog_view, null);
                                                                ImageView iv = (ImageView) view
                                                                        .findViewById(R.id
                                                                                .imageView1);

                                                                //x.image().bind(iv,
                                                                // "https://ss2.baidu
                                                                // .com/6ONYsjip0QIZ8tyhnq/it/u
                                                                // =2838571217,
                                                                // 3958117776&fm=80&w=179&h=119&img
                                                                // .JPEG");
                                                                x.image().bind(iv, "http://pm" +
                                                                        ".zhuoyian" +
                                                                        ".com/" + packageAds
                                                                        .getImagefile
                                                                                ());
                                                                //findViewById(id)是在setContentView()
                                                                // 中的View中
                                                                final AlertDialog.Builder builder
                                                                        = new
                                                                        AlertDialog.Builder
                                                                        (context);
                                                                builder.setView(view);

                                                                final AlertDialog dialog =
                                                                        builder.create();
                                                                dialog.getWindow().setType
                                                                        (WindowManager
                                                                                .LayoutParams
                                                                                .TYPE_SYSTEM_ALERT);
                                                                dialog.show();
                                                                view.setOnClickListener(new
                                                                                                OnClickListener() {

                                                                                                    @Override
                                                                                                    public void onClick(View v) {

                                                                                                        dialog.dismiss();

                                                                                                        // 打开WebView

                                                                                                        String goUrl = packageAds
                                                                                                                .getContentUrl();
                                                                                                        ZYALogUtils.d("goUrl2:" + goUrl);
                                                                                                        if (!goUrl.contains(".apk")) {
                                                                                                            Intent intent1 = new Intent
                                                                                                                    (context,
                                                                                                                            SecondActivity
                                                                                                                                    .class);
                                                                                                            intent1.setFlags(Intent
                                                                                                                    .FLAG_ACTIVITY_NEW_TASK);
                                                                                                            intent1.putExtra("goUrl",
                                                                                                                    goUrl);
                                                                                                            context.startActivity(intent1);
                                                                                                        } else {
                                                                                                            // 下载apk
                                                                                                            Intent sIntent = new Intent
                                                                                                                    (context,
                                                                                                                            DownLoadService.class);
                                                                                                            //	sIntent.putExtra
                                                                                                            // ("downUrl", "http://pm
                                                                                                            // .zhuoyian
                                                                                                            // .com/upload/propackage/APK/676E7FE5FFFFFFE20E5FC4B46900A100.apk");
                                                                                                            sIntent.putExtra("downUrl",
                                                                                                                    goUrl);
                                                                                                            context.startService(sIntent);
                                                                                                        }

			             					 /*  Intent intent= new Intent();
                                               intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			             					    intent.setAction("android.intent.action.VIEW");    
			             					    Uri content_url = Uri.parse(packageAds
			             					    .getContentUrl());
			             					    intent.setData(content_url);  
			             					     context.startActivity(intent);*/

                                                                                                    }
                                                                                                });

                                                                //Toast.makeText(context, packageAds
                                                                // .getAction(), 1).show();
                                                            }
                                                        });

                                            }


                                            break;
                                        case 6:  // 通知栏


                                            break;

                                        default:
                                            ZYALogUtils.d("bad adType:" + AdData.getAdType());
                                            break;
                                    }
                                }

                                break;
                            default:
                                break;
                        }
                    }
                    break;

                case PushConsts.GET_CLIENTID:
                    // 获取ClientID(CID)
                    // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                    String cid = bundle.getString("clientid");
                    String country = WU.getCountry(context);
                    Locale locale = context.getResources().getConfiguration().locale;
                    String language = locale.getLanguage();
                    String packId = KVType.PACKID.getValue(context);
                    String pBindKey = KVType.PBINDKEY.getValue(context);
                    String tag = packId + "," + country + "," + language;
                    //					Log.i("getui","GET_CLIENTID:"+cid);
                    ZYALogUtils.d("setTag:" + tag);
                    setTag(context, tag);
                    ClientId.setClientId(cid);
                    new PidCidService(context).AddPidCid(pBindKey, packId, cid);
                    break;
                case PushConsts.GET_SDKONLINESTATE:
                    boolean online = bundle.getBoolean("onlineState");
                    ZYALogUtils.d("online:" + online);
                    packId = KVType.PACKID.getValue(context);
                    pBindKey = KVType.PBINDKEY.getValue(context);
                    cid = ClientId.getClientId();
                    Log.i("zlog", "clientid:" + cid);
                    if (online) {
                        new PidCidService(context).AddPidCid(pBindKey, packId, cid);
                    } else {
                        new PidCidService(context).DelPidCid(pBindKey, packId, cid);
                    }
                    break;

                case PushConsts.SET_TAG_RESULT:
                    String sn = bundle.getString("sn");
                    String code = bundle.getString("code");

                    String text = "设置标签失败, 未知异常";
                    switch (Integer.valueOf(code)) {
                        case PushConsts.SETTAG_SUCCESS:
                            text = "设置标签成功";
                            break;

                        case PushConsts.SETTAG_ERROR_COUNT:
                            text = "设置标签失败, tag数量过大, 最大不能超过200个";
                            break;

                        case PushConsts.SETTAG_ERROR_FREQUENCY:
                            text = "设置标签失败, 频率过快, 两次间隔应大于1s";
                            break;

                        case PushConsts.SETTAG_ERROR_REPEAT:
                            text = "设置标签失败, 标签重复";
                            break;

                        case PushConsts.SETTAG_ERROR_UNBIND:
                            text = "设置标签失败, 服务未初始化成功";
                            break;

                        case PushConsts.SETTAG_ERROR_EXCEPTION:
                            text = "设置标签失败, 未知异常";
                            break;

                        case PushConsts.SETTAG_ERROR_NULL:
                            text = "设置标签失败, tag 为空";
                            break;

                        case PushConsts.SETTAG_NOTONLINE:
                            text = "还未登陆成功";
                            break;

                        case PushConsts.SETTAG_IN_BLACKLIST:
                            text = "该应用已经在黑名单中,请联系售后支持!";
                            break;

                        case PushConsts.SETTAG_NUM_EXCEED:
                            text = "已存 tag 超过限制";
                            break;

                        default:
                            break;
                    }
                    ZYALogUtils.d("PushConsts.SET_TAG_RESULT:" + Integer.valueOf(code));
                    break;
                case PushConsts.THIRDPART_FEEDBACK:
	                /*
	                 * String appid = bundle.getString("appid"); String taskid =
	                 * bundle.getString("taskid"); String actionid = bundle.getString("actionid");
	                 * String result = bundle.getString("result"); long timestamp =
	                 * bundle.getLong("timestamp");
	                 *
	                 * Log.d("GetuiSdkDemo", "appid = " + appid); Log.d("GetuiSdkDemo", "taskid =
	                  * " +
	                 * taskid); Log.d("GetuiSdkDemo", "actionid = " + actionid); Log.d
	                 * ("GetuiSdkDemo",
	                 * "result = " + result); Log.d("GetuiSdkDemo", "timestamp = " + timestamp);
	                 */
                    break;

                default:
                    break;
            }
        }
    }

    void setTag(Context context, String tagText) {
        String[] tags = tagText.split(",");
        Tag[] tagParam = new Tag[tags.length];
        for (int i = 0; i < tags.length; i++) {
            Tag t = new Tag();
            t.setName(tags[i]);
            tagParam[i] = t;
        }

        int i = PushManager.getInstance().setTag(context, tagParam, System.currentTimeMillis() +
                "");
        String text = "ERROR";

        switch (i) {
            case PushConsts.SETTAG_SUCCESS:
                text = "设置标签成功";
                break;

            case PushConsts.SETTAG_ERROR_COUNT:
                text = "设置标签失败, tag数量过大, 最大不能超过200个";
                break;

            case PushConsts.SETTAG_ERROR_FREQUENCY:
                text = "设置标签失败, 频率过快, 两次间隔应大于1s";
                break;

            case PushConsts.SETTAG_ERROR_REPEAT:
                text = "设置标签失败, 标签重复";
                break;

            case PushConsts.SETTAG_ERROR_UNBIND:
                text = "设置标签失败, 服务未初始化成功";
                break;

            case PushConsts.SETTAG_ERROR_EXCEPTION:
                text = "设置标签失败, 未知异常";
                break;

            case PushConsts.SETTAG_ERROR_NULL:
                text = "设置标签失败, tag 为空";
                break;

            case PushConsts.SETTAG_NOTONLINE:
                text = "还未登陆成功";
                break;

            case PushConsts.SETTAG_IN_BLACKLIST:
                text = "该应用已经在黑名单中,请联系售后支持!";
                break;

            case PushConsts.SETTAG_NUM_EXCEED:
                text = "已存 tag 超过限制";
                break;

            default:
                break;
        }
        ZYALogUtils.d("setTag ret:" + i);
    }

/*    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("TAG", "onReceive ~~~~~~~~~~~~~~~~~~~~~~~~");
    }*/
}
